package com.shengdan.pocket_file.pocketfile;

/**
 * author: ChenShengDan .
 * date:   2023/1/7
 * sence:
 */
public class Utils {

    public static int checkNetSegment(String mask, String ip1, String ip2) {
        String[] maskStr = mask.split("\\.");
        String[] ip1Str = ip1.split("\\.");
        String[] ip2Str = ip2.split("\\.");

        if (ip1Str.length != 4 || ip2Str.length != 4) {//若ip数组长度没有4则非法
            return 1;
        }

        String maskBin = intToBin(maskStr);
        String ip1Bin = intToBin(ip1Str);
        String ip2Bin = intToBin(ip2Str);

        if (maskBin == "1" || ip1Bin == "1" || ip2Bin == "1") {//若每个字段不在0—255范围则抛出1，非法
            return 1;
        }

        while (maskBin.length() != 32) {//掩码有可能出现255.0的情况，需要补0
            maskBin += "0";
        }

        String result1Bin = maskAndIp(maskBin, ip1Bin);
        String result2Bin = maskAndIp(maskBin, ip2Bin);

        if (result1Bin.equals(result2Bin)) {
            return 0;
        }
        return 2;
    }


    private static String intToBin(String[] s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length; i++) {
            if (Integer.parseInt(s[i]) >= 0 && Integer.parseInt(s[i]) <= 255) {
                String temp = Integer.toBinaryString(Integer.parseInt(s[i]));
                while (temp.length() != 8) {
                    temp = "0" + temp;
                }
                sb.append(temp);
            } else
                return "1";
        }
        return sb.toString();
    }

    private static String maskAndIp(String s1, String s2) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            char c = (char) (s1.charAt(i) & s2.charAt(i));//每位相与，其实没必要
            sb.append(String.valueOf(c));
        }
        return sb.toString();
    }






}
